package com.hymjweb.demo.hymj.system_maintenance.permission.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hymjweb.demo.framework.menu.bean.MenuBean;
import com.hymjweb.demo.framework.menu.service.MenuService;
import com.hymjweb.demo.framework.result.MIniUIGridResultMap;
import com.hymjweb.demo.framework.sys.BaseService;
import com.hymjweb.demo.framework.sys.SysConstant;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import com.hymjweb.demo.hymj.system_maintenance.permission.bean.PermissionPojo;
import com.hymjweb.demo.hymj.system_maintenance.permission.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PermissionService extends BaseService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuService menuService;

    private List<MenuBean> menuBeanList;

    public List<PermissionPojo> jsonArrayConvertToPojoList(JSONArray jsonArray) {
        if (jsonArray == null || jsonArray.isEmpty()) {
            return null;
        }
        List<PermissionPojo> permissionPojoList = new ArrayList<>();
        // 接收 json 数组
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            PermissionPojo pojo = jsonObject.toJavaObject(PermissionPojo.class);
            pojo.setId(this.getSysStrId());
            permissionPojoList.add(pojo);
        }
        return permissionPojoList;
    }


    public List<PermissionPojo> getPermissionPojoListNoPage(Map param) {
        return permissionMapper.getPermissionPojoListNoPage(param);
    }


    public Object getPageList(Map param) {
        // 分页初始化
        this.pageListInit(param);

        // 获取查询列表
        List list = getPermissionPojoListNoPage(param);

        // 封装到PageInfo对象中
        PageInfo pageInfo = new PageInfo(list);

        MIniUIGridResultMap resultMap = new MIniUIGridResultMap(pageInfo);
        return resultMap;
    }


    /**
     * 刷新授权菜单资源
     *
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public int refreshAuthMenuResource() {

        // 1.获取当前所有菜单位列表
        menuBeanList = menuService.getNoPageList(null);

        // 2.以menuBeanList为基础，构造可以插入授权资源表的List对象
        List<PermissionPojo> permissionPojoList = new ArrayList<>();

        for (MenuBean menuBean : menuBeanList) {
            PermissionPojo permissionPojo = new PermissionPojo();
            permissionPojo.setId(menuBean.getId());
            permissionPojo.setPid(menuBean.getPid());
            String pids = getPid(menuBean.getId());
            pids = pids.substring(0, pids.length() - 1);
            permissionPojo.setPids(pids);
            permissionPojo.setName(menuBean.getName());
            permissionPojo.setResourceTypeId(SysConstant.XT_DIC_PERMISSION_TYPE.MEMU.getId());
            permissionPojo.setUrl(menuBean.getUrl());
            permissionPojo.setPermissionCode("menu:" + menuBean.getId());
            permissionPojo.setMenuId(null);
            permissionPojo.setMenuName(null);
            permissionPojoList.add(permissionPojo);
        }

        if (permissionPojoList.isEmpty()) {
            return SysConstant.INT_ZERO;
        }

        // 3.先删除授权资源表中的所有菜单资源
        int affectRows = permissionMapper.deletePermissionByResourceTypeId(SysConstant.XT_DIC_PERMISSION_TYPE.MEMU.getId());

        // 4.批量插入授权的菜单资源
        int insertAffectRows = permissionMapper.batchInsertPermission(permissionPojoList);


        if (insertAffectRows <= SysConstant.INT_ZERO) {
            return SysConstant.INT_ZERO;
        }

        return insertAffectRows;
    }


    public String getPid(String nodeId) {
        MenuBean currentMenuBean = getMenuBeanById(nodeId);
        if (currentMenuBean != null) {
            String pid = currentMenuBean.getPid() + ",";
            //参数patrolConfigEntity.getConfigParentId()表示当前节点的父节点ID
            String returnConfigName = getPid(currentMenuBean.getPid());
            return returnConfigName + pid;
        } else {
            return "";
        }
    }

    /**
     * 根据id,获取菜单对象
     *
     * @param nodeId
     * @return
     */
    private MenuBean getMenuBeanById(String nodeId) {
        if (DataTypeUtil.isEmptyStr(nodeId)) {
            return null;
        }

        if (menuBeanList == null || menuBeanList.isEmpty()) {
            return null;
        }

        for (MenuBean bean : menuBeanList) {
            if (bean.getId().equals(nodeId)) {
                return bean;
            }
        }
        return null;
    }


    public List<PermissionPojo> queryPermissionPojoByPermissionCode(String permissionCode) {
        if (DataTypeUtil.isEmptyStr(permissionCode)) {
            return null;
        }
        return permissionMapper.queryPermissionPojoByPermissionCode(permissionCode);
    }

    public boolean checkMenuId(List<PermissionPojo> permissionPojoList) {
        if (permissionPojoList == null || permissionPojoList.isEmpty()) {
            return false;
        }

        boolean flag = true;
        Long resourceTypeId = permissionPojoList.get(0).getResourceTypeId();
        String menuId = permissionPojoList.get(0).getMenuId();
        if (resourceTypeId != null && menuId != null) {
            for (PermissionPojo pojo : permissionPojoList) {
                if (!resourceTypeId.equals(pojo.getResourceTypeId()) || !menuId.equals(pojo.getMenuId())) {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }

    public boolean checkUnique(List<PermissionPojo> permissionPojoList) {
        boolean flag = false;
        if (permissionPojoList != null && permissionPojoList.size() > 0) {
            for (PermissionPojo pojo : permissionPojoList) {
                List<PermissionPojo> pojoList = queryPermissionPojoByPermissionCode(pojo.getPermissionCode());
                if (pojoList != null && pojoList.size() > 0) {
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }

    public Object loadMenuTree() {
        Map<String, Object> map = new HashMap<>();
        map.put("keyResourceTypeId", SysConstant.XT_DIC_PERMISSION_TYPE.MEMU.getId());
        List<PermissionPojo> permissionPojoMenuList = permissionMapper.getPermissionPojoListNoPage(map);
        return permissionPojoMenuList;
    }

    /**
     * 根据ids  '','','','' 检索对应的所有资源
     *
     * @param ids
     * @return
     */
    public List<PermissionPojo> queryPermissionPojoByIds(String ids) {
        return permissionMapper.queryPermissionPojoByIds(ids);
    }

    @Transactional(rollbackFor = {Exception.class})
    public int add(PermissionPojo permissionPojo) throws Exception {
        if (permissionPojo == null) {
            throwException("添加授权资源参数错误!");
        }

        permissionPojo.setId(this.getSysStrId());

        return permissionMapper.insert(permissionPojo);
    }


    @Transactional(rollbackFor = {Exception.class})
    public int update(PermissionPojo permissionPojo) throws Exception {
        if (permissionPojo == null) {
            throwException("更新授权资源参数错误!");
        }
        return permissionMapper.update(permissionPojo);
    }

    @Transactional(rollbackFor = {Exception.class})
    public int deletePermissioByMenuId(String menuId) throws Exception {
        if (DataTypeUtil.isEmptyStr(menuId)) {
            throwException("删除权限资源参籹错误!");
        }
        return permissionMapper.deletePermissioByMenuId(menuId);
    }
}
